/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Object;

import com.sun.xml.internal.ws.resources.HttpserverMessages;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author PhongLK60473
 */
public class User implements Serializable {

    private int id;
    private String Username;
    private String Password;
    private String Roles;
    private int RoleId;
    private boolean Admin = false;
    private boolean Customer = false;
    private boolean Guest = true;
    private boolean Loged;
    private boolean Active=false;

    Hashtable Orders;
    private float TotalPrice;

    public User() {
        Orders = new Hashtable();
    }

    public User(int id, String Username, String Password, int RoleId,boolean Active) {
        this.id = id;
        this.Username = Username;
        this.Password = Password;
        this.RoleId = RoleId;
        this.Active = Active;
    }

    public boolean isActive() {
        return Active;
    }

    public void setActive(boolean Active) {
        this.Active = Active;
    }

    public User(int id) {
        this.id = id;
        Database db = new Database();
        if (db.isOK) {
            PreparedStatement stm = null;
            ResultSet rs = null;

            String strSQL = "SELECT username,password,roleid FROM Users WHERE id = ? ";
            try {
                stm = db.con.prepareStatement(strSQL);
                stm.setInt(1, this.id);
                rs = stm.executeQuery();

                if (rs.next()) {
                    this.Username = rs.getString(1);
                    this.Password = rs.getString(2);
                    this.RoleId = rs.getInt("roleid");
                    if (this.RoleId == 1) {
                        this.Admin = true;
                        this.Customer = false;
                        this.Guest = false;
                    } else if (this.RoleId == 2) {
                        this.Customer = true;
                        this.Admin = false;
                        this.Guest = false;
                    }
                } else {
                    this.Guest = true;
                    this.Customer = false;
                    this.Admin = false;
                    System.out.println("Login(){ Select user has no row }");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("User(){ SQL : " + e.getMessage());
            } finally {
                try {
                    rs.close();
                    stm.close();
                    db.con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        } else {
            System.out.println("Login(){ Connect database failed }");
        }
    }

    public void login() {
//        System.out.println("login called");
        Database db = new Database();
        if (db.isOK) {
            PreparedStatement stm = null;
            ResultSet rs = null;

            String strSQL = "SELECT * FROM Users WHERE username = ? "
                    + "AND password = ? "
                    + "AND isActive = ?";
            try {
                stm = db.con.prepareStatement(strSQL);
                stm.setString(1, this.Username);
                stm.setString(2, this.Password);
                stm.setBoolean(3, true);
                rs = stm.executeQuery();

                System.out.println("User:" + Username);
                System.out.println("Password:" + Password);

                if (rs.next()) {
                    this.id = rs.getInt(1);
                    this.RoleId = rs.getInt("roleid");
                    if (this.RoleId == 1) {
                        this.Admin = true;
                        this.Customer = false;
                        this.Guest = false;
                    } else if (this.RoleId == 2) {
                        this.Customer = true;
                        this.Admin = false;
                        this.Guest = false;
                    }

                    System.out.println("role:" + RoleId);

                } else {
                    this.Guest = true;
                    this.Customer = false;
                    this.Admin = false;
                    this.Loged=false;
                    System.out.println("Login(){ Select user has no row }");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("User(){ SQL : " + e.getMessage());
            } finally {
                try {
                    rs.close();
                    stm.close();
                    db.con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        } else {

            System.out.println("Login(){ Connect database failed }");
        }
    }

    public boolean register(User user) {
        Database db = new Database();
        if (db.isOK) {
            PreparedStatement stm = null;
            ResultSet rs = null;

            String strSQL = "INSERT INTO Users (username,password,roleid,isActive) "
                    + "VALUES(?, ?, ?)";
            try {
                stm = db.con.prepareStatement(strSQL);
                stm.setString(1, this.Username);
                stm.setString(2, this.Password);
                stm.setInt(3, this.RoleId);
                stm.setBoolean(4, true);
                int row = stm.executeUpdate();
                if (row > 0) {
                    return true;
                } else {
                    return false;
                }
            } catch (SQLException e) {
                System.out.println("Register(){ SQL : " + e.getMessage());
                return false;
            } finally {
                try {
                    rs.close();
                    stm.close();
                    db.con.close();
                } catch (SQLException e) {
                    return false;
                }
            }
        } else {
            System.out.println("Register(){ Connect database failed }");
            return false;
        }

    }

    public boolean addOrder(int bookId) {
        Order oldOrder = (Order) Orders.get(bookId + "");
        float price;
        if (oldOrder == null) {
            Order newOrder = new Order(bookId);
            price = newOrder.getPrice();
            Orders.put(bookId + "", newOrder);
        } else {
            oldOrder.setQuantity(oldOrder.getQuantity() + 1);
            price = oldOrder.getPrice();
        }
        TotalPrice += price;
        return true;
    }

    public boolean isAdmin() {
        return Admin;
    }

    public void setAdmin(boolean Admin) {
        this.Admin = Admin;
    }

    public boolean isCustomer() {
        return Customer;
    }

    public int getId() {
        return id;
    }

    public int getRoleId() {
        return RoleId;
    }

    public void setRoleId(int RoleId) {
        this.RoleId = RoleId;
    }

    public void setId(int id) {
        this.id = id;
    }

    public boolean isLoged() {
        return Loged;
    }

    public void setLoged(boolean Loged) {
        this.Loged = Loged;
    }

    public void setCustomer(boolean Customer) {
        this.Customer = Customer;
    }

    public boolean isGuest() {
        return Guest;
    }

    public void setGuest(boolean Guest) {
        this.Guest = Guest;
    }

    public String getPassword() {
        return Password;
    }

    public void setPassword(String Password) {
        this.Password = Password;
    }

    public String getRoles() {
        return Roles;
    }

    public void setRoles(String Roles) {
        this.Roles = Roles;
    }

    public float getTotalPrice() {
        return TotalPrice;
    }

    public void setTotalPrice(float TotalPrice) {
        this.TotalPrice = TotalPrice;
    }

    public String getUsername() {
        return Username;
    }

    public void setUsername(String Username) {
        this.Username = Username;
    }

    public User(String Username, String Password) {
        this.Username = Username;
        this.Password = Password;
    }

    public User(int id, String Username, String Password, int RoleId) {
        this.id = id;
        this.Username = Username;
        this.Password = Password;
        this.RoleId = RoleId;
    }

    public User(HttpServletRequest request) {
        this(request.getParameter("txtUsername"), request.getParameter("txtPassword"));
    }

    public static boolean isLoging(HttpServletRequest request) {
//        System.out.println(request.getParameter("txtUsername"));
//        System.out.println(request.getParameter("txtPassword"));

        if (request.getParameter("txtUsername") == null) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean isRegistering(HttpServletRequest request) {
        if (request.getParameter("txtUsername") == null) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean Register(HttpServletRequest request) {
        String msg = "";
        boolean rt = false;
        Database db = new Database();
        String username = request.getParameter("txtUsername");
        String password = request.getParameter("txtPassword");
        if (username == null || password == null
                || username.equals("") || password.equals("")) {
            msg = "Invalid input!";
        } else {
            if (db.isOK) {
                PreparedStatement stm = null;
                ResultSet rs = null;

                String strSQL = "INSERT INTO Users (username,password,roleid,"
                        + "isActive) VALUES(?, ?, ?, ?)";
                try {
                    stm = db.con.prepareStatement(strSQL);
                    stm.setString(1, username);
                    stm.setString(2, password);
                    stm.setInt(3, 2);
                    stm.setBoolean(4, true);
                    int row = stm.executeUpdate();

                    if (row > 0) {
                        msg = "Register success,please login!";
                        rt = true;
                    }
                } catch (SQLException e) {
                    msg = "Cannot register!";
                    System.out.println("User(){ SQL : " + e.getMessage());
                } finally {
                    try {
                        //rs.close();
                        stm.close();
                        db.con.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                msg = "Connect database fail.";
                System.out.println("Login(){ Connect database failed }");
            }
        }
        request.getSession().setAttribute("RegisterMsg", msg);
        return rt;
    }

    public static void Logout(HttpServletRequest request) {
        request.getSession().invalidate();
    }
    public static Hashtable getAllRoles(){
        Hashtable rt = new Hashtable();
        Database db = new Database();

        if(db.isOK){
            String strSQL;
            PreparedStatement stm=null;
            ResultSet rs = null;
            try {
                strSQL = "SELECT * FROM userRoleTypes";
                stm = db.con.prepareStatement(strSQL);
                rs = stm.executeQuery();
                while(rs.next()){
                    rt.put(rs.getInt(1)+"", rs.getString(2));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try{
                    rs.close();
                    stm.close();
                    db.con.close();
                } catch (SQLException e){
                }
            }
        }else{
            
        }
        return rt;
    }
    public static User[] getAllUsers(){
        ArrayList alUser = new ArrayList();
        Hashtable roles = User.getAllRoles();

        Database db = new Database();

        if(db.isOK){
            String strSQL;
            PreparedStatement stm=null;
            ResultSet rs = null;
            try {
                strSQL = "SELECT * FROM Users";
                stm = db.con.prepareStatement(strSQL);
                rs = stm.executeQuery();
                while(rs.next()){
                    User newUser = new User(rs.getInt(1), rs.getString(2),
                            rs.getString(3), rs.getInt(4), rs.getBoolean(5));
                    newUser.Roles = (String) roles.get(newUser.getRoleId()+"");
                    alUser.add(newUser);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try{
                    rs.close();
                    stm.close();
                    db.con.close();
                } catch (SQLException e){
                }
            }
        }else{

        }
        User[] users = new User[alUser.size()];
        alUser.toArray(users);
        return users;
    }
    public static boolean activeUser(HttpServletRequest request){
        boolean rt=false;
        try{
            String action=request.getParameter("action").toString();
            int userid = Integer.parseInt(request.getParameter("userid"));
            if(action.equals("ActiveUser")){
                rt=activeUser(userid, true);
            }else if(action.equals("DeactiveUser")){
                rt=activeUser(userid, false);
            }else{
                rt=false;
            }
        }catch(Exception e){
            rt=false;
        }
        if(rt){
            Page.setMessage("Active user success!", request);
        }else{
            Page.setMessage("Cannot active user!", request);
        }
        return rt;
    }
    public static boolean activeUser(int id,boolean active){
        boolean rt=false;
        Database db = new Database();

        if(db.isOK){
            String strSQL;
            PreparedStatement stm=null;
            int rs = -1;
            try {
                strSQL = "UPDATE Users SET isActive = ? "
                        + " WHERE id = ?";
                stm = db.con.prepareStatement(strSQL);
                stm.setBoolean(1,active);
                stm.setInt(2, id);
                rs = stm.executeUpdate();
                if(rs>0){
                    rt = true;
                }else{
                    rt = false;
                }
                
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try{
                    stm.close();
                    db.con.close();
                } catch (SQLException e){
                }
            }
        }else{

        }
        return rt;
    }
}
